<?php

namespace seecms;

use seecms\lib\builder\Page;
use seecms\lib\builder\PageParse;
use seecms\lib\Twig;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;

class SeeView
{
    protected $assign = [];

    /**
     * @param $key
     * @param $vars
     * @return void
     */
    public function assign($key, $vars)
    {
        $this->assign[$key] = $vars;
    }

    /**
     * @param $name
     * @param array $vars
     * @return string
     */
    public function fetch($name, array $vars = []): string
    {
        $name .= '.twig';

        $vars = array_merge($this->assign, $vars);

        try {
            $twig = Twig::instance()->environment();
            $html = $twig->render($name, $vars);
        } catch (LoaderError|RuntimeError|SyntaxError $error) {
            $class = get_class($error);
            $line = $error->getLine();
            $file = $error->getFile();
            $message = $error->getMessage();
            $html = <<<EOF
<div style="margin-top: 30px"></div>
<h1>$message</h1>
<div style="margin-top: 30px"></div>
<h3>$class in  $file line $line </h3>
EOF;
        }

        return $html;
    }

    /**
     * 这里是统一的页面布局
     * @param Page $page
     * @param string $template
     * @return string
     */
    public function page(Page $page, string $template = 'public/index'): string
    {
        $parse = new PageParse($page->getDictionary());
        $page_title = $page->getTitle();
        $alters = $parse->alerts($page->getAlerts());
        $query = $parse->query($page->getQuery());
        $columns = $parse->columnsTransfer($page->getActionColumns());
        $resource_route = $page->getResourceRoute();
        $left_toolbars = $parse->toolbars($page->getLeftToolbars());
        $right_toolbars = $page->getRightToolbars();

        return $this->fetch($template, compact(
            'page_title',
            'alters',
            'query',
            'columns',
            'resource_route',
            'left_toolbars',
            'right_toolbars'
        ));
    }
}